<template>
  <hu-modal :title="formData.id ? '修改-模板' : '新增-模板'" :show-modal.sync="addModal" :loading="loading" @close="cancel" @submit="addFrom">
    <el-steps align-center :active="activeNum" finish-status="success" style="margin: 10px 0;">
      <el-step title="配置审批流程参数"></el-step>
      <el-step title="配置审批节点及其审批角色或人员"></el-step>
      <el-step title="点击保存完成配置"></el-step>
    </el-steps>
    <el-row>
      <el-col :span="8" :xs="24">
        <div class="border_tent" style="height: 300px;">
          <el-form ref="queryForm" :model="formData" :rules="rulesSon" label-width="80px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="审批流程" prop="name">
                  <el-input v-model="formData.name" placeholder="请输入审批流程名称"   />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="系统模块" prop="moduleId">
                  <el-cascader :options="optionsList" :props="casProps"  style="width: 100%" @change="getModule" v-model="formData.moduleId" :show-all-levels="false">
                  </el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item>
                  <el-button type="primary" icon="el-icon-plus"  @click="updateNum">下一步</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-col>
      <el-col :span="8" :xs="24" v-if="activeNum >= 1">
        <div class="border_tent" style="padding-bottom: 100px;min-height: 300px;" @click.stop>
          <template>
            <div v-for="(item, index) in dataList" :key="item.id">
              <div class="df_tent">
                <div class="left_user">{{ item.name }}</div>
                <div @click="getMessage(item, index)" class="head">
                  <img @dragstart="faceImgDrag(index)" @ondragenter="ondragenter" @drop="faceDrop($event, index)" @dragover="allowDrop" class="icon_img_id" :src="comSrc(item.type)" :class="dataItem === index ? 'avatar' : ''" style="width: 44px; height: 44px" />
                </div>
                <div class="r_tem" @click.stop>
                  <transition name="fade">
                    <div class="" v-show="indexVer === index">
                      <div v-if="item.type == 0 || item.type == 1" class="tent_tem">
                        <div style="
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                          ">
                          <el-button style="margin: 0 5px" class="delete_buttons"  icon="el-icon-minus" plain @click="deleteList(index)">移除节点</el-button>
                        </div>
                      </div>
                    </div>
                  </transition>
                </div>
              </div>
              <div v-show="dataList.length" style="display: flex; justify-content: center">
                <div style="width: 2px; border: 1px solid #eaeaea; height: 80px"></div>
              </div>
            </div>
            <div>
              <div @click.stop class="df_tent">
                <div class="left_user">增加节点</div>
                <div @click="addMessage('add')" class="head">
                  <img src="@/assets/images/carbon3.png" :class="indexVer === 'add' ? 'avatar' : ''" style="width: 44px; height: 44px" />
                </div>
                <div class="r_tem" @click.stop>
                  <transition name="fade">
                    <div class="" v-show="indexVer === 'add'">
                      <div class="tent_tem">
                        <el-button style="margin: 0 5px 10px" class="add_buttons"  icon="el-icon-s-check" plain @click="addAudit">审核节点</el-button>
                        <el-button style="margin: 0 5px" class="add_buttons"  icon="el-icon-s-promotion" plain @click="addFry">抄送节点</el-button>
                      </div>
                    </div>
                  </transition>
                </div>
              </div>
            </div>
          </template>
        </div>
      </el-col>
      <el-col :span="8" :xs="24" v-if="dataItem || dataItem === 0">
        <div class="border_tent">
          <transition name="fade">
            <div>
              <el-form ref="queryForm1" :model="dataList[dataItem]" label-width="80px">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="节点名称" prop="title">
                      <el-input v-model="dataList[dataItem].name" placeholder="请输入节点名称"   />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="审批类别" prop="approveRule">
                      <el-radio-group :disabled="dataList[dataItem].type !== 0" v-model="dataList[dataItem].approveRule">
                        <el-radio :label="0">或签</el-radio>
                        <el-radio :label="1">会签</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div v-show="!dataList[dataItem].approveTypeIsRoles">
                <div style="
                    display: flex;
                    border-top: 1px solid #eaeaea;
                    padding-top: 20px;
                  ">
                  <el-select   v-model="orgId" style="width: 30%" @change="getUser" placeholder="请选择单位" >
                    <el-option v-for="item in orgList" :key="item.id" :value="item.id" :label="item.name">
                    </el-option>
                  </el-select>
                  <el-select  style="flex: 1"  remote collapse-tags multiple  :remote-method="remoteMethod" v-model="userData" placeholder="根据姓名，工号搜索">
                    <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                  <el-button type="primary" style="float: right" icon="el-icon-plus"  @click="addUserList">添加</el-button>
                </div>
                <div style="display: flex; padding-top: 20px">
                  <el-input v-model="search" placeholder="请输入关键字进行过滤"   />
                </div>
                <hu-table maxHeight="400" style="margin-top: 10px" :tableData="
                    dataList[dataItem].tableData.filter(
                      (data) =>
                        !search ||
                        data.name
                          .toLowerCase()
                          .includes(search.toLowerCase()) ||
                        data.name.indexOf(search) !== -1
                    )
                  " :loading="loading" :tableCol="tableCol">
                  <template v-slot:operate="{ row }">
                    <el-button type="text" @click="handleDelete(row)">删除</el-button>
                  </template>
                  <template v-slot:roles="{ row }">
                    <el-tag style="font-size: 12px; margin: 0 5px" v-for="(item, index) in row.roles" :key="index">{{ item.name }}</el-tag>
                  </template>
                </hu-table>
              </div>
            </div>
          </transition>
        </div>
      </el-col>
    </el-row>
  </hu-modal>
</template>

<script>
import * as http from "@/api/system/workflow";
import { misData, orgData } from "@/api/user.js";

export default {
  name: "AuditMonitoringWorkflowIndex",
  props: {
    showModal: {
      type: Boolean,
      default: false,
    },
    formDataP: {
      type: Object,
      default: {
        type: 1,
        status: 1,
        name: undefined,
        module: undefined,
        moduleId: [],
        remark: undefined,
      },
    },
  },
  computed: {
    comSrc() {
      return (type) => {
        return require(`@/assets/images/carbon${type}.png`);
      };
    },
    // get 系统模块
    optionsList() {
      return this.$store.getters.topbarRouters;
    },
  },
  watch: {
    showModal(val) {
      this.addModal = val;
      this.getFormDataP();
    },
    addModal(val) {
      this.$emit("update:showModal", val);
    },
  },
  created() {
    this.getOrgList();
    this.getRoleList();
  },
  data() {
    return {
      orgList: [],
      orgId: "",
      search: "",
      tableCol: [
        {
          title: "序号",
          type: "index",
          showOverflowTooltip: false,
          width: "55",
        },
        {
          title: "姓名",
          key: "name",
        },
        {
          title: "操作",
          slot: "operate",
          align: "center",
          show: true,
        },
      ],
      tableCol1: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: "55",
          showOverflowTooltip: false,
          show: true,
        },
        {
          title: "角色",
          key: "name",
          align: "center",
          show: true,
        },
        {
          title: "操作",
          slot: "operate",
          align: "center",
          show: true,
        },
      ],
      total: 0, // table total
      // 选中人员 list
      userData: [],
      userData1: [],
      userList: [], // 人员list
      roleList: [], // 角色列表
      // 拖到图标 第一位置
      oneIndex: undefined,
      // 节点选中项
      dataItem: undefined,
      // 节点选中项 index
      indexVer: undefined,
      // 节点 List
      dataList: [],
      // 确认按钮 loading
      loading: false,
      // 弹窗
      addModal: false,
      // 步骤条选中项
      activeNum: 0,
      // 表单校验
      rulesSon: {
        name: [
          { required: true, message: "模板名称不能为空", trigger: "blur" },
        ],
        moduleId: [
          { required: true, message: "系统模块不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "定时发布不能为空", trigger: "change" },
        ],
      },
      casProps: {
        value: "id",
        label: "titleName",
        children: "children",
      },
      formData: {
        type: 0,
        status: 1,
        name: undefined,
        module: undefined,
        moduleId: [],
        remark: undefined,
      },
    };
  },
  methods: {
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        let params = { pageSize: 300, orgId: this.orgId, name: query };
        misData(params).then(({ result }) => {
          this.loading = false;
          this.userList = result.records;
        });
      }
    },
    getOrgList() {
      orgData().then(({ result }) => {
        this.orgList = result;
      });
    },
    getUser(id) {
      if (id) {
        let params = { pageSize: 300, orgId: this.orgId };
        misData(params).then(({ result }) => {
          this.userList = result.records;
        });
      } else {
        this.userList = [];
      }
    },
    getFormDataP() {
      let val = this.formDataP;
      this.cancel();
      if (val.id) {
        http.getListDet({ id: val.id }).then(({ result, stateCode }) => {
          if (stateCode === 200) {
            this.activeNum = 3;
            this.formData = {
              id: result.id,
              type: result.type,
              status: result.status,
              name: result.name,
              module: result.module,
              remark: result.remark,
              moduleId: val.moduleTreeIds.slice(1),
            };
            // this.parentIds(result.moduleId);
            this.dataList = result.nodes.map((prams, index) => {
              return {
                id: prams.id,
                name: prams.name,
                type: prams.type,
                approveRule: prams.approveRule,
                approveTypeIsRoles: prams.approveTypeIsRoles,
                approveTypeIsUsers: !prams.approveTypeIsRoles,
                approveUsers: prams.users,
                approveRoleIds: prams.approveRoleIds
                  ? prams.approveRoleIds.split(",")
                  : [],
                tableData: prams.users.map((e) => {
                  return {
                    id: e.userId,
                    userId: e.userId, // 用户id
                    name: e.userName, // 用户名称
                    userCode: e.userCode, // 工号
                    no: e.userCode, // 工号
                    orgId: e.orgId, // 直属组织机构id 公司或班组，部门
                    orgName: e.orgName,
                    orgType: e.businessType,
                    businessType: e.businessType,
                  };
                }),
              };
            });
          }
        });
      }
    },

    parentIds(id) {
      http.parentIds(id).then(({ result }) => {
        this.$set(this.formData, "moduleId", result.splice(1));
      });
    },
    getModule(ids) {
      if (!ids) return;
      this.$set(
        this.formData,
        "module",
        this.$utils.searchTree(ids[ids.length - 1], this.optionsList)[0].meta
          .title
      );
    },
    // 删除人员
    handleDelete(row) {
      let data = this.dataList[this.dataItem].tableData;
      data.splice(
        data.findIndex((item) => item.id == row.id),
        1
      );
      this.dataList[this.dataItem].tableData = data;
      // key
      let key = this.dataList[this.dataItem].approveUsers;
      key.splice(
        key.findIndex((item) => item.userId == row.userId),
        1
      );
      this.dataList[this.dataItem].approveUsers = key;
    },
    getRoleList() {
      http.getRoleList().then(({ result, stateCode }) => {
        if (stateCode === 200) {
          this.roleList = result;
        }
      });
    },
    //
    getTableData(ids) {
      return this.$utils.arrayDiff(this.userList, "id", ids);
    },
    // add user list
    addUserList() {
      let arrData = this.$utils.arrayDiff(this.userList, "id", this.userData);
      this.dataList[this.dataItem].tableData = this.$utils.merge(
        this.dataList[this.dataItem].tableData,
        arrData,
        "id"
      );
      // key
      this.dataList[this.dataItem].approveUsers = this.dataList[
        this.dataItem
      ].tableData.map((e) => ({
        id: e.id,
        userId: e.id, // 用户id
        userName: e.name, // 用户名称
        userCode: e.no, // 工号
        orgId: e.orgId, // 直属组织机构id 公司或班组，部门
        orgName: e.orgName,
        orgType: e.businessType,
      }));
    },
    // 图片按下
    faceImgDrag(index) {
      this.oneIndex = index;
    },
    // 图片抬起
    faceDrop(event, index) {
      if (!this.oneIndex && this.oneIndex !== 0) return;
      this.dataList.splice(
        this.oneIndex,
        1,
        ...this.dataList.splice(index, 1, this.dataList[this.oneIndex])
      );
      this.oneIndex = undefined;
      this.dataItem = index;
      event.preventDefault();
    },
    allowDrop(event) {
      // 阻止浏览器的一个默认行为 浏览器默认不允许拖拽
      event.preventDefault();
    },
    ondragenter(event) {
      // 阻止浏览器的一个默认行为 浏览器默认不允许拖拽
      event.preventDefault();
    },

    // 审核节点
    addAudit() {
      let add = {
        name: "各单位业务主管审批",
        type: 0,
        approveRule: 0,
        approveTypeIsRoles: false,
        approveTypeIsUsers: true,
        approveUsers: [],
        approveRoleIds: [],
        id: this.generateId(),
        tableData: [],
      };
      this.dataList.push(add);
      this.dataItem = this.dataList.length - 1;
      // 弹窗隐藏
      this.indexVer = undefined;
    },
    // 抄送节点
    addFry() {
      let add = {
        name: "抄送人",
        type: 1,
        approveTypeIsRoles: false,
        approveTypeIsUsers: true,
        approveUsers: [],
        approveRoleIds: [],
        id: this.generateId(),
        tableData: [],
      };
      this.dataList.push(add);
      this.dataItem = this.dataList.length - 1;
      // 弹窗隐藏
      this.indexVer = undefined;
    },
    // 删除节点
    deleteList(index) {
      this.dataList.splice(index, 1);
      this.dataItem = undefined;
      this.indexVer = undefined;
    },
    // 点击节点
    getMessage(item, index) {
      this.userData = undefined;
      this.orgId = undefined;

      this.dataItem = index;
      this.indexVer = index;
    },
    addMessage(index) {
      this.indexVer = index;
    },
    // 前端生成id方法
    generateId() {
      const s = [];
      const hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      // bits 12-15 of the time_hi_and_version field to 0010
      s[14] = "4";
      // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";
      const uuid = s.join("");
      return uuid;
    },
    // 提交
    addFrom() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          let params = {
            ...this.formData,
            moduleId: this.formData.moduleId[this.formData.moduleId.length - 1],
            nodes: this.dataList.map((prams) => {
              return {
                ...prams,
                approveUserIds: prams.approveUsers.map((e) => e.userId),
                approveTypeIsUsers: !prams.approveTypeIsRoles,
                tableData: undefined,
                id: undefined,
              };
            }),
          };
          if (this.formData.id != undefined) {
            http
              .updateList(params)
              .then(() => {
                this.loading = false;
                this.$modal.msgSuccess("修改成功");
                this.addModal = false;
                this.$emit("update");
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            http
              .addList(params)
              .then(() => {
                this.loading = false;
                this.$modal.msgSuccess("新增成功");
                this.addModal = false;
                this.$emit("update");
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("queryForm");

      this.formData = {
        type: 0,
        status: 1,
        name: undefined,
        module: undefined,
        moduleId: [],
        remark: undefined,
      };
      if (this.$store.getters.itself == "23031001") {
        this.$set(this.formData, "type", 0);
      } else {
        this.$set(this.formData, "type", 1);
      }
      this.userData = undefined;
      this.orgId = undefined;
      this.indexVer = undefined;
      this.dataItem = undefined;
      this.dataList = [];
      this.activeNum = 0;
    },
    // 切换下一个表单
    updateNum() {
      this.activeNum = 1;
    },
    bodyCloseMenus() {
      this.indexVer = undefined;
    },
  },
  mounted() {
    document.addEventListener("click", this.bodyCloseMenus);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.bodyCloseMenus);
  },
};
</script>
<style>
.el-step.is-horizontal.is-center .is-success {
  color: #496dff;
  border: #496dff !important;
}
.border_tent {
  overflow: auto;
  margin: 10px;
  padding: 20px;
  height: 100%;
  box-shadow: 0px 1px 9px 0px rgba(0, 35, 133, 0.15);
}
</style>
<style lang="scss" scoped>
.df_tent {
  display: flex;
  justify-content: center;
  align-items: center;
  & div {
    padding: 0 20px;
  }
  .left_user {
    text-align: right;
    width: 170px;
  }
  .head {
    width: 70px;
    display: flex;
    justify-content: center;
    img {
      transition: 0.3s;
    }
    img:hover {
      transform: scale(1.1);
    }
    img:active {
      transform: scale(1.2);
    }
    .avatar {
      transform: scale(1.1);
    }
  }
  .r_tem {
    position: relative;
    top: 0;
    width: 170px;
    .tent_tem {
      position: absolute;
      left: 10px;
      width: 150px;
      box-shadow: 0px 0px 8px 0px rgba(55, 90, 228, 0.16);
      border-radius: 4px;
      padding: 20px;
    }
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.25s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity: 0;
}
</style>
